<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <link rel="stylesheet" href='/plug-in/pear/css/pear.css' media="all">
    <link rel="stylesheet" href='/css/base.css' media="all">
    <script src="/plug-in/jquery/jquery-3.5.1.min.js" charset="utf-8"></script>
    <script src='/plug-in/layui/layui.js' charset="utf-8"></script>
    <script src='/plug-in/lay-config.js' charset="utf-8"></script>
    <style>
        .layui-btn-container .layui-btn {margin-bottom: 0;}
        .form-box {display: none;padding: 45px;}
        #auth-tree{flex-grow: 1;overflow: auto;}
        #auth-tree::-webkit-scrollbar {width: 4px;height: 4px;}
    </style>
</head>
<body>
<div class="page-content" shiro:hasPermission="system.role.list">
    <table id="menuTreeTb" class="layui-border-box layui-table-view"></table>
</div>

<div class="form-box">
    <form class="layui-form" action="" lay-filter="form-obj" style="width: 500px; margin: 0 auto;">
        <div class="layui-form-item" id="parent-menu">
            <label class="layui-form-label towexin-form-label">上级角色：</label>
            <div class="layui-input-block">
                <div id="select-tree" style="margin-right: 2px;" class="xm-select-demo"></div>
            </div>
        </div>
        <div class="layui-form-item m-name layui-hide">
            <div class="layui-input-block">
                <input type="text" name="pid" class="layui-input">
                <input type="text" name="id" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-href">
            <label class="layui-form-label towexin-form-label layui-required">角色名称：</label>
            <div class="layui-input-block">
                <input type="text" name="roleName" lay-verify="required" placeholder="请输入角色名称" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-href">
            <label class="layui-form-label towexin-form-label layui-required">角色标识：</label>
            <div class="layui-input-block">
                <input type="text" name="mark" lay-verify="required" placeholder="请设置角色标识" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item m-name">
            <label class="layui-form-label towexin-form-label layui-required" id="showName">角色备注：</label>
            <div class="layui-input-block">
                <textarea placeholder="请输入内容" name="roleRemarks" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: right;">
                <button type="submit" id="submit-type" class="pear-btn pear-btn-primary" lay-submit=""
                        lay-filter="add">立即提交
                </button>
            </div>
        </div>
    </form>
</div>

<div class="auth-box" style="display: none; padding: 10px;box-sizing: border-box;height: 100%">
    <div style="display: flex; flex-direction: column;height: 100%">
        <blockquote style="padding: 8px 15px;font-weight: bold;margin-bottom: 0" class="layui-elem-quote" id="auth-role"></blockquote>
        <fieldset class="layui-elem-field layui-field-title" style="margin-bottom: 5px"><legend>授权列表</legend></fieldset>
        <div id="auth-tree" class="demo-tree-more"></div><hr>
        <div style="text-align: right">
            <button type="button" class="pear-btn pear-btn-xs" lay-demo="authCancel">取消</button>
            <button type="button" class="pear-btn pear-btn-primary pear-btn-xs set-auth" lay-demo="setAuth">确认</button>
        </div>
    </div>

</div>

<script type="text/html" id="toolbarTop">
    <div class="layui-btn-container">
        <button shiro:hasPermission="system.role.list" class="layui-btn layui-btn-sm layui-bg-black" lay-event="refresh"><span class="fa fa-refresh"
                                                                                        title="刷新表格"
                                                                                        aria-hidden="true"></span>
        </button>
        <button shiro:hasPermission="system.role.add" class="layui-btn layui-btn-sm layui-bg-blue" lay-event="newModel"><span class="fa fa-plus-circle"
                                                                                        aria-hidden="true"></span> 添加
        </button>
    </div>
</script>
<!-- 操作列 -->
<script type="text/html" id="auth-state">
    <button shiro:hasPermission="system.role.authorization" class="layui-btn layui-btn-warm layui-btn-xs" lay-event="auth">授权</button>
    <button shiro:hasPermission="system.role.edit" class="layui-btn layui-btn-success layui-btn-xs" lay-event="edit">编辑</button>
    <button shiro:hasPermission="system.role.delete" class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>
</script>

<script type="text/html" id="status">
    <input shiro:hasPermission="system.role.status" type="checkbox" lay-skin="switch" {{d.status===true?"checked":""}} lay-filter="status" lay-text="启用|禁用" value="{{d.id}}">
    <input shiro:lacksPermission="system.role.status" disabled type="checkbox" lay-skin="switch" {{d.status===true?"checked":""}} lay-text="启用|禁用">
</script>
<script type="text/html" id="default">
    <input shiro:hasPermission="system.role.default" type="checkbox" lay-skin="switch" {{d.defaultRole===true?"checked":""}} lay-filter="default" lay-text="TRUE|FALSE" value="{{d.id}}">
    <input shiro:lacksPermission="system.role.default" disabled type="checkbox" lay-skin="switch" {{d.defaultRole===true?"checked":""}} lay-text="TRUE|FALSE">
</script>

<script type="text/javascript">
    let form = layui.form, layer = layui.layer, treeTable = null, element = layui.element,
        xmSelect = null, tree = layui.tree, util = layui.util;

    let treeTb = null, selectTree = null;

    function getTree() {
        $.ajax({
            url: "/role/selectRoleTree",
            success: function (res) {
                selectTree.update({
                    data: res.data
                })
                selectTree.changeExpandedKeys(true)
            }
        })
    }
</script>

<!--授权操作-->
<script type="text/javascript" th:inline="none" shiro:hasPermission="system.role.authorization">
    //按钮事件
    util.event('lay-demo', {
        setAuth: (othis) => {
            var checkedData = tree.getChecked('role-tree'); //获取选中节点的数据
            $.ajax({
                type: "POST",
                url: "/role/authorization",
                data: {rId: rId, authIdJson: JSON.stringify(getIdsByRecursion(checkedData))},
                success: (res) => {
                    if (res.code === 200) {
                        if (res.code === 200) {
                            layer.closeAll()
                            layer.msg("操作成功")
                        } else {
                            layer.closeAll('loading')
                            layer.msg("操作失败")
                        }
                    }
                },
                error: () => {
                    layer.closeAll('loading')
                    layer.msg("请求失败")
                }
            })
        },
        setAuthDefault: ()=>{
            var checkedData = tree.getChecked('role-tree'); //获取选中节点的数据
            $.ajax({
                type: "POST",
                url: "/role/default-author",
                data: {authIdJson: JSON.stringify(getIdsByRecursion(checkedData))},
                success: function (res) {
                    if (res.code === 200) {
                        if (res.code === 200) {
                            layer.closeAll()
                            layer.msg("操作成功")
                        } else {
                            layer.closeAll('loading')
                            layer.msg("操作失败")
                        }
                    }
                },
                error: function () {
                    layer.closeAll('loading')
                    layer.msg("请求失败")
                }
            })
        },
        authCancel: function (othis) {
            layer.closeAll()
        }
    });

    function getIdsByRecursion(data) {
        let ids = [];
        $.each(data, function (index, d) {
            ids.push(d.id)
            if (d.children && d.children.length > 0) {
                ids = ids.concat(getIdsByRecursion(d.children))
            }
        })
        return ids;
    }

    //  权限树初始化
    tree.render({
        elem: '#auth-tree',
        onlyIconControl: true,
        showCheckbox: true,
        id: 'role-tree'
    });
</script>

<!--添加-->
<script type="text/javascript" th:inline="none">
    layui.use(["xmSelect"], function () {
        xmSelect = layui.xmSelect

        selectTree = xmSelect.render({
            el: '#select-tree',
            autoRow: true,
            name: "authorityList",
            tips: '请选择上级角色',
            layVerify: 'required',
            direction: 'down',
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                indent: 35,
                expandedKeys: true,
                //是否严格遵守父子模式
                strict: false,
                //是否开启极简模式
                simple: false,
                clickCheck: true,
                clickExpand: false
            },
            radio: true,
            model: {
                type: 'absolute',
            },
            on: function (data) {
                if (data.arr.length > 0) {
                    form.val("form-obj", {
                        pid: data.arr[0].value
                    });
                }
            },
            theme: {
                color: '#1c86bb',
            },
            toolbar: {
                show: true,
                list: ['ALL', 'REVERSE', 'CLEAR']
            },
            height: '300px',
        })

        getTree()
    })
</script>

<!--保存与更新请求-->
<script type="text/javascript" th:inline="none">
    layui.use(["popup"], function () {
        let popup = layui.popup
        form.on('submit(add)', function (data) {
            layer.load()
            $.ajax({
                url: data.field.id!==null&&data.field.id!==""?"/role/update":"/role/save",
                type: "POST",
                data: data.field,
                success: function (res) {
                    layer.closeAll('loading')
                    if (res.code === 200) {
                        treeTb.refresh();
                        getTree()
                        layer.closeAll()
                    } else if(res.code===401){
                        popup.warning(res.msg)
                    } else {
                        popup.warning(res.msg)
                    }
                },
                error: function () {
                    layer.closeAll('loading')
                    popup.failure("服务出错")
                }
            })
            return false;
        });
    })
</script>


<!--列表-->
<script type="text/javascript" th:inline="none" shiro:hasPermission="system.role.list">
    layui.use(["treeTable", "popup"], function () {
        let popup = layui.popup
        treeTable = layui.treeTable;

        treeTb = treeTable.render({
            elem: '#menuTreeTb',
            toolbar: "#toolbarTop",
            defaultToolbar: false,
            skin: "line",
            tree: {
                iconIndex: 0,           // 折叠图标显示在第几列
                isPidData: true,        // 是否是id、pid形式数据
                idName: 'id',  // id字段名称
                pidName: 'pid',     // pid字段名称
                getIcon: function (d) {  // 自定义图标
                    // d是当前行的数据
                    if (d.pid === "no" && d.type !== "1") {  // 判断是否有子集
                        return '<i class="fa fa-window-maximize" aria-hidden="true"></i>';
                    } else if (d.type === "1") {
                        return '<i class="fa fa-home" aria-hidden="true"></i>'
                    } else {
                        if (d.menuHref !== "" && d.menuHref != null) {
                            return '<i class="fa fa-link" aria-hidden="true"></i>';
                        } else {
                            return '<i class="fa fa-cog" aria-hidden="true"></i>';
                        }
                    }
                }
            },
            cols: [[
                {field: 'roleName', title: '角色名称', minWidth: 120},
                {field: 'mark', title: '标识', minWidth: 120},
                {title: '默认角色', width: 120, templet: "#default"},
                {field: 'roleRemarks', title: '备注', minWidth: 120},
                {title: '状态', width: 100, templet: "#status"},
                {field: "createdTime", width: 160, sort: true, title: '创建时间',},
                {field: "updateTime", width: 160, sort: true, title: '修改时间',},
                {templet: '#auth-state', width: 160, unresize: false, align: 'center', title: '操作', fixed: 'right'},
            ]],
            //height: "full-40",
            reqData: function (data, callback) {
                $.ajax({
                    url: "/role/selectAll",
                    success: function (res) {
                        callback(res.data);
                    },
                })
            }
        });

        //监听状态操作
        form.on('switch(status)', function(obj){
            layer.load()
            $.ajax({
                url: "/role/changeStatus",
                data: {id: obj.value, status: obj.elem.checked},
                success: function (res) {
                    if (res.code === 200) {
                        layer.closeAll()
                        layer.tips("操作成功", obj.othis);
                    } else if(res.code === 401){
                        layer.closeAll()
                        layer.tips(res.msg, obj.othis);
                    }else {
                        layer.closeAll('loading')
                        layer.tips("操作失败", obj.othis);
                    }
                    treeTb.reload();
                },
                error(){
                    layer.closeAll('loading')
                    layer.msg("服务出错")
                    treeTb.reload();
                }
            })
        });

        //监听设置默认角色
        form.on('switch(default)', function(obj){
            layer.load()
            $.ajax({
                url: "/role/set-default",
                data: {id: obj.value, defaultRole: obj.elem.checked},
                success: function (res) {
                    if (res.code === 200) {
                        layer.closeAll()
                        layer.tips("操作成功", obj.othis);
                    } else if(res.code === 401){
                        layer.closeAll()
                        layer.tips(res.msg, obj.othis);
                    }else {
                        layer.closeAll('loading')
                        layer.tips("操作失败", obj.othis);
                    }
                    treeTb.reload();
                },
                error(){
                    layer.closeAll('loading')
                    layer.msg("服务出错")
                    treeTb.reload();
                }
            })
        });

        treeTable.on('tool(menuTreeTb)', function (obj) {
            let data = obj.data;
            let layEvent = obj.event;

            if (layEvent === 'del') {
                layer.confirm('确定删除 <span style="color: red; font-weight: 800">' + data.roleName + '</span> 么？', {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    layer.close(index);
                    layer.load()
                    $.ajax({
                        url: '/role/deleteOne',
                        data: {id: data.id},
                        success: function (result) {
                            layer.closeAll('loading')
                            if (result.code === 200) {
                                treeTb.reload();
                                getTree()
                                popup.success("删除成功")
                            } else {
                                popup.success("删除失败")
                            }
                        },
                        error: function () {
                            layer.closeAll('loading')
                            popup.success("服务错误")
                        }
                    });
                });
            }else if (layEvent === 'edit') {
                selectTree.setValue([data.pid]);
                form.val("form-obj", data)

                layer.open({
                    type: 1,
                    area: ["40%", '60%'],
                    //maxmin: true,
                    content: $(".form-box"),
                    title: "编辑",
                    scrollbar: false
                })
            }else if (layEvent === "auth") {
                $(".pear-btn.set-auth").attr("lay-demo", "setAuth")
                window.rId = data.id
                $.ajax({
                    url: "/role/getAuthority",
                    data: {id: data.id},
                    success: function (res) {
                        $("#auth-role").html("授权角色："+'<span class="layui-badge layui-bg-cyan">'+data.roleName+'</span>')
                        tree.reload('role-tree', {data: res.data});
                        layer.open({
                            type: 1,
                            area: ["50%", '90%'],
                            //maxmin: true,
                            content: $(".auth-box"),
                            title: false,
                            scrollbar: false
                        })
                    }
                })
            }
        });

        // 头部工具栏点击事件
        treeTable.on('toolbar(menuTreeTb)', function (obj) {
            switch (obj.event) {
                case "refresh":
                    treeTb.reload()
                    break;
                case 'newModel':
                    selectTree.setValue([])
                    form.val("form-obj", {
                        pid: "",
                        id: "",
                        roleName: "",
                        roleRemarks: ""
                    });
                    layer.open({
                        type: 1,
                        area: ["40%", '60%'],
                        //maxmin: true,
                        content: $(".form-box"),
                        title: "新增",
                        scrollbar: false
                    })
                    break;
            }
        });

    })
</script>

</body>
</html>